<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>JQ拖拽到网格</title>
		<style type="text/css">
			body{
				margin: 0;
			}
			#grid{
				width: 511px;
				height: 511px;
				background: gray;
			}
			#block{
				width: 50px;
				height: 50px;
				background: red;
				position: absolute;
				left: 1px;
				top: 1px;
			}
		</style>
		<script src="jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			$(function (){
				
				//生成网格
				for (var i=0; i<10; i++) {
					for (var j=0; j<10; j++) {
						$('<div>').css({
							'width': 50,
							'height': 50,
							'background': '#fff',
							'position':'absolute',
							'left': 1+i*51,
							'top': 1+j*51
						}).appendTo($('#grid'));
					}
				}
				
				//拖拽
				$('#block').mousedown(function (ev){
					var disX = ev.pageX - $(this).offset().left;
					var disY = ev.pageY - $(this).offset().top;
					$(document).mousemove(function (ev){
						var mL = ev.pageX - disX;
						if (mL<1) {
							mL = 1;
						} else if (mL>$('#grid').outerWidth()-$('#block').width()-1) {
							mL = $('#grid').outerWidth()-$('#block').width()-1;
						}
						var mT = ev.pageY - disY;
						if (mT<1) {
							mT = 1;
						} else if (mT>$('#grid').outerHeight()-$('#block').height()-1) {
							mT = $('#grid').outerHeight()-$('#block').height()-1;
						}
						$('#block').css({
							'left': mL,
							'top': mT
						});
					})
					$(document).mouseup(function (){
						//网格判断
							//51 = $('#block').width() + 1;
						var tL = $('#block').offset().left;
						if (tL%51<25) {
							tL = tL - tL%51 + 1;
						} else {
							tL = tL - tL%51 + 51 + 1;
						}
						var tT = $('#block').offset().top;
						if (tT%51<25) {
							tT = tT - tT%51 + 1;
						} else {
							tT = tT - tT%51 + 51 + 1;
						}
						$('#block').animate({
							'left': tL,
							'top': tT
						});
						$(this).off();
					})
					return false;
				})
				
			})
		</script>
	</head>
	<body>
		<div id="grid"></div>
		<div id="block"></div>
	</body>
</html>
